#Using for Display wafermap

import os
import wx
import re
import glob
import string
import wx.lib.colourselect as  csel

#DieWidth=10

Bins={}
FlagStartX=0
FlagEndX=0
FlagStartY=0
FlagEndY=0
BinColours={1:(  0,255,  0),
            2:(255,  0,  0),
            3:(200, 60,180),  
            4:(  0,  0,255), 
            5:(  0,  0,  0), 
            6:(255,100,130),
            7:(255,128,  0), 
            8:(255,255,  0), 
            9:(128,  0,  0), 
            10:(127,  0,255),
            11:(128,128,  0),
            12:(255,128,  0), 
            13:(128,128,255),
            14:(128,  0,128),  
            15:(127,  0,255), 
            16:(  0,255,255), 
            17:(255,  0,255), 
            18:(230,255,230), 
            19:(200,204, 51),
            20:( 70,165,185), 
            21:(185,185,170),
            22:(160, 95,146)
            }


def ReadBHTCData(self,LotDataPath,WaferId,SortType):
    if not os.path.isdir(LotDataPath):
        print ("The LotDataPath:",LotDataPath," is not exist! when you use ReadBHTCData function!")
        return(False)
    else:           
        #BHTCFileFH=open("temp.bhtc","r")
        os.chdir(os.path.join(LotDataPath,"Bhtc"))
        TempFiles=glob.glob("*.bhtc")
        for TempFile in TempFiles:
            TempArray=re.split(r"_|\.",TempFile)
            if string.upper(TempArray[5])==string.upper(SortType) and int(TempArray[6])==int(WaferId):
                global Bins
                global FlagStartX
                global FlagEndX
                global FlagStartY
                global FlagEndY
                BHTCFileFH=open(TempFile,"r")
                for Line in BHTCFileFH.readlines():
                    if re.search(r"((\s+){0,}(-){0,1}\d+\|){4,}",Line,re.I):
                        Temp=re.split(r"\|",Line)
                        TempX=int(Temp[2])
                        TempY=int(Temp[3])
                        if FlagStartX>TempX:
                            FlagStartX=TempX
                        if FlagEndX<TempX:
                            FlagEndX=TempX
                        if FlagStartY>TempY:
                            FlagStartY=TempY
                        if FlagEndY<TempY:
                            FlagEndY=TempY
                        TempKey="".join(("X",str(TempX),"Y",str(TempY)))
                        Bins[TempKey]=Temp[1].strip()
        return(True)
    
class CreateMap(wx.Panel):    
    def __init__(self,parent):
        wx.Panel.__init__(self,parent,-1 )
        self.parent=parent
        self.SetBackgroundColour('white')
        self.offsetX=8
        self.offsetY=4
        
        XSizer=(FlagEndX-FlagStartX+self.offsetX)*DieWidth
        YSizer=(FlagEndY-FlagStartY+self.offsetY)*DieWidth
        self.SetSizeWH(XSizer,YSizer)
        #self.SetAutoLayout(True)
        self.Bind(wx.EVT_PAINT,self.Draw)
        self.Bind(wx.EVT_MOTION,self.OnMotion)
    def Draw(self,event):
        dc=wx.BufferedPaintDC(self)
        for Indey in range(0,FlagEndY-FlagStartY+self.offsetY):
            for Index in range(0,FlagEndX-FlagStartX+self.offsetX):
                TempKey="".join(("X",str(Index+FlagStartX-2),"Y",str(Indey+FlagStartY-2)))
                if Bins.has_key(TempKey):
                    BrushColour=BinColours[int(Bins[TempKey])]
                    dc.SetPen(wx.Pen(wx.BLACK))
                    dc.SetBrush(wx.Brush(BrushColour))
                    dc.DrawRectangle(DieWidth*(Index),DieWidth*(Indey),DieWidth,DieWidth)
                else:  
                    dc.SetPen(wx.Pen(wx.WHITE))
                    dc.SetBrush(wx.Brush(wx.WHITE))
                    dc.DrawRectangle(DieWidth*(Index),DieWidth*(Indey),DieWidth,DieWidth)
    def OnMotion(self,event):
        CoordX=event.GetX()/DieWidth+FlagStartX-2
        CoordY=event.GetY()/DieWidth+FlagStartY-2
        TempKey="".join(("X",str(CoordX),"Y",str(CoordY)))
        if Bins.has_key(TempKey):
            self.parent.StaticBinValue.SetLabel("    "+str(Bins[TempKey])+"     ")
            self.parent.StaticCoordValue.SetLabel(" ("+str(CoordX)+","+str(CoordY)+" )  ")
            #print ("Bin:",Bins[TempKey],"; Coord:","("+str(CoordX)+","+str(CoordY)+")")
class BinColourSet(wx.Panel):
    def __init__(self,parent):
        global BinColours
        wx.Panel.__init__(self, parent, -1)
        self.SetAutoLayout(True)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(mainSizer)
        buttonData = [
            ("PASS",   (0, 255, 0),   wx.DefaultSize, ""),
            ("BIN 2",  (255, 0, 0),   wx.DefaultSize, ""),
            ("BIN 3",  (200, 60, 180),     wx.DefaultSize, ""),
            ("BIN 4",  (0, 0, 255),     wx.DefaultSize, ""),
            ("BIN 5",  (0, 0 ,  0),   wx.DefaultSize, ""),
            ("BIN 6",  (255, 100, 130), wx.DefaultSize, ""),
            ("BIN 7",  (255, 128, 0),   wx.DefaultSize, ""),
            ("BIN 8",  (255, 255, 0),     wx.DefaultSize, ""),
            ("BIN 9",  (128, 0, 0),     wx.DefaultSize, ""),
            ("BIN 10",  (127, 0, 255),   wx.DefaultSize, ""),
            ("BIN 11",  (128, 128, 0), wx.DefaultSize, ""),
            ("BIN 12",  (255, 128, 0),   wx.DefaultSize, ""),
            ("BIN 13",  (128, 128, 255),     wx.DefaultSize, ""),
            ("BIN 14",  (128, 0, 128),     wx.DefaultSize, ""),
            ("BIN 15",  (127, 0, 255),   wx.DefaultSize, ""),
            ("BIN 16",   (0, 255, 255), wx.DefaultSize, ""),
            ("BIN 17",  (255, 0, 255),   wx.DefaultSize, ""),
            ("BIN 18",  (230, 255, 230),     wx.DefaultSize, ""),
            ("BIN 19",  (200, 204, 51),    wx.DefaultSize, ""),
            ("BIN 20",  (70, 165, 185),   wx.DefaultSize, ""),
            ("BIN 21",  (185, 185, 170), wx.DefaultSize, ""),
            ("BIN 22",  (160, 95, 146),   wx.DefaultSize, ""),
            ]

        self.buttonRefs = [] # for saving references to buttons
        buttonSizer = wx.FlexGridSizer(6, 4) # sizer to contain all the example buttons
        # build each button and save a reference to it
        for name, color, size, label in buttonData:
            b = csel.ColourSelect(self, -1, label, color, size = size)
            b.Bind(csel.EVT_COLOURSELECT, self.OnSelectColour)
            self.buttonRefs.append((name, b))  # store reference to button
            buttonSizer.AddMany([
                (wx.StaticText(self, -1, name), 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                (b, 0, wx.ALL, 3),
                ])
        mainSizer.Add(buttonSizer, 0, wx.ALL, 3)
        self.Layout()
    def OnSelectColour(self,event):
        print("name :%s Colour selected: %s" % (name, str(event.GetValue())))
class MainFrame(wx.Frame):
    def __init__(self,parent,title,LotDataPath,WaferId,SortType):
        MyFrame=wx.Frame.__init__(self,parent,-1,title,
                                  style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_TOOL_WINDOW)
        self.SetBackgroundColour('white')
        #self.SetAutoLayout(True)
        global Bins
        global FlagStartX
        global FlagEndX
        global FlagStartY
        global FlagEndY
        global BinColours
        global DieWidth
        
        LotNum=os.path.basename(LotDataPath)
        Flag=ReadBHTCData(self,LotDataPath,WaferId,SortType)
        if Flag:
            if (FlagEndY-FlagStartY)<60 or (FlagEndX-FlagStartX)<60:
                DieWidth=7
            elif (FlagEndY-FlagStartY)<50 or (FlagEndX-FlagStartX)<50:
                DieWidth=10
            elif (FlagEndY-FlagStartY)<40 or (FlagEndX-FlagStartX)<40:
                DieWidth=15
            elif (FlagEndY-FlagStartY)<30 or (FlagEndX-FlagStartX)<30:
                DieWidth=20
            elif (FlagEndY-FlagStartY)<20 or (FlagEndX-FlagStartX)<20:
                DieWidth=25    
            else:
                DieWidth=5 
            XSizer=(FlagEndX-FlagStartX+34)*DieWidth
            YSizer=(FlagEndY-FlagStartY+26)*DieWidth
            self.SetSizeWH(XSizer,YSizer)
            #BinColourSet(self)
            
            self.CreateMap=CreateMap(self)
            self.StaticLotNum=wx.StaticText(self,id=-1,label="LotNum:  "+LotNum,pos=wx.Point(20, 5))            
            self.StaticWaferId=wx.StaticText(self,id=-1,label="   WaferId:  "+WaferId,pos=wx.Point(20, 5))
            self.StaticSortType=wx.StaticText(self,id=-1,label="   SortType:  "+SortType,pos=wx.Point(20, 5))
            self.StaticBinDesp=wx.StaticText(self,id=-1,label="   Bin:  ",pos=wx.Point(20, 5))
            self.StaticBinValue=wx.StaticText(self,-1,"        ",pos=wx.Point(60, 5))
            self.StaticBinValue.SetBackgroundColour('green')
            self.StaticCoordDesp=wx.StaticText(self,-1,"     Coord:  ",pos=wx.Point(100, 5))
            self.StaticCoordValue=wx.StaticText(self,-1,"             ",pos=(140,5))
            self.StaticCoordValue.SetBackgroundColour('green')
            
            HBox1=wx.BoxSizer(wx.HORIZONTAL)  #horizontal
            HBox1.AddMany([(self.StaticLotNum,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                        (self.StaticWaferId,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                        (self.StaticSortType,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                        (self.StaticBinDesp,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                        (self.StaticBinValue,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                        (self.StaticCoordDesp,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                        (self.StaticCoordValue,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
                        ])
            #style=LI_HORIZONTAL
            
            
            ColourBox = wx.FlexGridSizer(6, 4) # sizer to contain all the example buttons
            # build each button and save a reference to it
            BinColoursKeys=sorted(BinColours.keys())
            for Key in BinColoursKeys:
                b = csel.ColourSelect(self, -1,"", BinColours[Key])                
                ColourBox.AddMany([
                    (wx.StaticText(self, -1,  "Bin:"+str(Key)),0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                    (b, 0, wx.ALL, 3),
                    ])
            
            HBox2=wx.BoxSizer(wx.HORIZONTAL)
            HBox2.AddMany([(self.CreateMap,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                        (ColourBox,0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,),
                          ])
            
            VBox1=wx.BoxSizer(wx.VERTICAL)
            VBox1.AddMany([(HBox1,0,wx.ALIGN_LEFT|wx.ALL,20),
                         (wx.StaticLine(self, -1, size=(1024,-1)), 0, wx.ALL, 5),
                         (HBox2,0,wx.ALIGN_LEFT|wx.ALL,20),
                         ])
            self.SetSizer(VBox1)
            self.SetAutoLayout(True)
            
        else:
            print "Run ReadBHTCData Fail!"
if __name__=='__main__':
    app=wx.PySimpleApp()
    frame=MainFrame(None,u"WaferMap Display",r"D:\Work\NewTestData\hed0409_bv65\h625153_0000988",r"10",r"Sort2")
    frame.Show(True)
    app.MainLoop()